package service

import (
	"admin100/app/dao"
	"admin100/app/model"
	"admin100/app/model/commonmodel"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"math"
)

var MailSmtpDataService = MailSmtpData{}

type MailSmtpData struct {
}

func (s *MailSmtpData) Add(r *model.MailSmtpDataMgrServicesAddReq) bool {

	columns := dao.MailSmtpData.Columns
	_, err := dao.MailSmtpData.Save(map[string]interface{}{
		columns.User:  r.User,
		columns.Host:  r.Host,
		columns.Port:  r.Port,
		columns.Pass:  r.Pass,
		columns.State: r.State,
	})
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	return true
}

func (s *MailSmtpData) Edit(r *model.MailSmtpDataMgrServicesEditReq) bool {
	columns := dao.MailSmtpData.Columns
	var upData = map[string]interface{}{}
	if r.Host != "" {
		upData[columns.Host] = r.Host
	}
	if string(r.Port) != "" {
		upData[columns.Port] = r.Port
	}
	if r.Pass != "" {
		upData[columns.Pass] = r.Pass
	}
	if string(r.State) != "" {
		upData[columns.State] = r.State
	}
	_, err := dao.MailSmtpData.Where(dao.MailSmtpData.Columns.User, r.User).Update(upData)
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	return true
}

func (s *MailSmtpData) Del(r *model.MailSmtpDataMgrServicesDelReq) bool {
	_, err := dao.MailSmtpData.Where(dao.MailSmtpData.Columns.User+" IN (?)", r.Users).Delete()
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	return true
}

func (s *MailSmtpData) List(r *model.MailSmtpDataMgrServiceListReq) (pageInfo commonmodel.PageInfo, data []*model.MailSmtpData) {
	nums, err := dao.MailSmtpData.Count()
	defErr.IfPanic(err, define.DataOptFail)
	pageInfo = commonmodel.PageInfo{
		Total: nums,
		Cur:   r.Page,
		PNum:  int(math.Ceil(float64(nums) / float64(r.PageSize))),
	}

	if r.Page > pageInfo.PNum {
		defErr.Panic(define.PageOverPageLimit)
	}

	data, err = dao.MailSmtpData.Page(r.Page, r.PageSize).All()
	defErr.IfPanic(err, define.DataOptFail)

	return pageInfo, data

}
